export default function createBrowserHistory() {
  const globalHistory = window.history;
  let listeners = [];
  let state;

  const notify = (newState) => {
    Object.assign(globalHistory, newState);
    listeners.forEach((listener) => listener(newState));
  };

  const go = (n) => {
    globalHistory.go(n);
  };

  const goBack = () => {
    // go(-1);
    globalHistory.back();
  };

  const goForward = () => {
    // go(1);
    globalHistory.forward();
  };

  const push = (pathname, nextState) => {
    const action = "PUSH";
    if (typeof pathname === "object") {
      state = pathname.state;
      pathname = pathname.pathname;
    } else {
      state = nextState;
    }

    globalHistory.pushState(state, null, pathname);

    const location = { state, pathname };
    notify({ action, location });
  };

  const listen = (listener) => {
    listeners.push(listener);
    return () => {
      listeners = listeners.filter((item) => item !== listener);
    };
  };

  window.addEventListener("popstate", () => {
    const location = {
      state: window.location.state,
      pathname: window.location.pathname,
    };
    // 当路径改变之后应该让 history 的监听函数执行，重新刷新组件
    notify({ action: "POP", location });
  });

  const history = {
    action: "POP",
    location: {
      pathname: window.location.pathname,
      state: window.location.state,
    },
    go,
    goBack,
    goForward,
    push,
    listen,
  };

  // 在 window 上挂载自己的 myHistory, 这样就可以在控制台使用
  window.myHistory = history;
  return history;
}
